import pandas as pd
from dateutil.parser import parse
import sys,os

url = '../data/stock_10_CSV/sh600000.day.csv'
if len(sys.argv) > 1:
    url = sys.argv[1]
file_name = url.split('/')[-1]
save_dir = '../data/output_csv'
isExists = os.path.exists(save_dir)
if not isExists:
    os.makedirs(save_dir)
save_url = save_dir+'/'+file_name.replace('.csv', '_out.csv')
print(save_url)

df = pd.read_csv(url, index_col=False, usecols=['date', 'open', 'high', 'low', 'close'])
df['date'] = df['date'].apply(lambda x: parse(str(x)))
df = df.set_index('date')


# 均线构建 (参数n为均线构建期间)
def ma(n):
    df['ma' + str(n)] = round(df['close'].rolling(window=n, min_periods=1).mean(), 2)


ma(5)  # 5日均线
ma(13)  # 20日均线
ma(27)  # 27日均线
# ma5>ma13就标示为1，否则为0
df['5-13'] = (df['ma5'] - df['ma13']).apply(lambda x: 1 if x > 0 else 0)

# 5-13金叉为1，死叉为-1，别的为0
def x_5_13(x):
    result = 0
    if x > 0:
        result = 1
    elif x < 0:
        result = -1
    return result

print(df['5-13'].diff())
df['5-13_X'] = (df['5-13'].diff()).apply(x_5_13)
# 今日27日均线大于昨日27日均线为1，否则为0
df['27diff'] = (df['ma27'].diff()).apply(lambda x: 1 if x > 0 else 0)
df.fillna(0)
df.to_csv(save_url)
print(df.head(50))